package ldh.im.base.service;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import ldh.im.ImConfig;
import ldh.im.base.CacheUserManager;
import ldh.im.base.ChannelGroupManager;
import ldh.im.base.ImSession;
import ldh.im.dto.business.ServerRedirectMessage;
import ldh.im.dto.base.SuccessResp;
import ldh.im.dto.business.P2pTextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TextMessageBusinessService implements BusinessService<P2pTextMessage> {

    private static final Logger LOGGER = LoggerFactory.getLogger(TextMessageBusinessService.class);

    @Override
    public void handle(ImSession imSession, P2pTextMessage msg) {
        Channel channel = imSession.getChannel();
//        LOGGER.info(String.format("receive message:" + JsonUtil.toJson(msg)));
        Long toUserId = msg.getToUserId();
        ChannelId channelId = (ChannelId) CacheUserManager.getInstance().getCache(toUserId, ImConfig.CHANNEL_ID);
        if (channelId != null) {
            Channel channelTo = ChannelGroupManager.getInstance().getChannel(channelId);
            if (channelTo != null && channelTo.isActive()) {
                ServerRedirectMessage serverP2pTextMessage = new ServerRedirectMessage(msg);
                channelTo.writeAndFlush(serverP2pTextMessage);
            }
        }

        SuccessResp s =  new SuccessResp(msg.getLocalSeq());
        channel.writeAndFlush(s);
    }
}
